package com.ideabove.yt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import com.ideabove.util.LogUtils;

import android.os.AsyncTask;

public class VodUrlGetter extends AsyncTask<String, Void, HttpResponse>{

    @Override
    protected HttpResponse doInBackground(String... urls) {
         
        HttpResponse response = null;
        HttpClient client = new DefaultHttpClient();        
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
        HttpGet request = new HttpGet(urls[0]);
        request.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");
        try {
            response = client.execute(request);
        }catch(ClientProtocolException e){
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }
         
        return response;
    }

    @Override
    protected void onPostExecute(HttpResponse response) {
        //super.onPostExecute(result);     
        try {        	
			String jsonStr = "";
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			boolean ttt = false;
			while((line = reader.readLine()) != null)
			{	
				String s = null;				
				s = StringEscapeUtils.unescapeJava(line);
				
				if(line.contains("ls.setItem('PIGGYBACK_DATA', \")]}")){
					ttt = true;
				}
				
				if(ttt){
					str.append(s);
				}
			}
			in.close();
			jsonStr = str.toString();
			jsonStr = jsonStr.substring(jsonStr.indexOf("{\""), jsonStr.indexOf("\");"));
			
//			LogUtils.splitAndLog("tt", jsonStr);
            
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}